import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import {
  ElMessageBox
} from "element-plus";
import {
  getDeviceListApi,
  createDeviceApi,
  updateDeviceApi,
  delDeviceApi,
  getDeviceShowApi,
  updateStatusApi
} from "@/api/device";
import { useRouter } from 'vue-router';
export function useCorps() {
  const routePath = useRouter().currentRoute.value.path
  const devType = routePath === '/device/list-outside'?'outside': routePath ==='/device/list-network'?'network':'plc'
  const form = reactive({
    page: 1,
    perPage: 10,
    module: devType,
    name: "",
    keyword: '',
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const indexMethod = (index: number) => {
    return index + 1;
  };
  let differentTable: TableColumnList = []
  const commonTable: TableColumnList = [
	  {
	    label: "ID",
	    prop: "deviceId",
	  },
	  {
	    label: "设备类型",
	    prop: "deviceType",
	    formatter: (row) => {
	    	return row.deviceType === 1?'提升机':'托盘'
	    }
	  },
	  {
	    label: "设备名称",
	    prop: "deviceName"
	  },
  ]
  if(devType === 'plc') {
	  if(routePath === '/device/list-plc') {
		  differentTable = [
		    {
		      label: "设备别名",
		      prop: "deviceAlias"
		    },
		    
		    {
		      label: "IP",
		      prop: "ipAddress"
		    },
		    {
		      label: "端口号",
		      prop: "portNumber"
		    },
		    {
		      label: "状态",
		      prop: "status",
		      cellRenderer: scope => (
		      	<el-switch
		      	  size={scope.props.size === "small" ? "small" : "default"}
		      	  v-model={scope.row.status}
		      	  active-value={1}
		      	  inactive-value={2}
		      	  active-text="启用"
		      	  inactive-text="禁用"
		      	  inline-prompt
		      	  onClick={() => switchStatus(scope as any)}
		      	/>
		      )
		    },
		    {
		      label: "操作",
		      fixed: "right",
		      slot: "operation"
		    }
		  ];
	  } else {
		  differentTable = [ {
		      label: "设备别名",
		      prop: "deviceAlias"
		    }]
	  }
	
  } else if(devType === 'outside'){
	  differentTable = [
	    
	    {
	      label: "设备编号",
	      prop: "deviceNo"
	    },
		{
		  label: "设备位置",
		  prop: "devicePos"
		},
		{
		  label: "IP",
		  prop: "ipAddress"
		},
		{
		  label: "端口号",
		  prop: "portNumber"
		},
		{
		  label: "状态",
		  prop: "status",
		  cellRenderer: scope => (
		  	<el-switch
		  	  size={scope.props.size === "small" ? "small" : "default"}
		  	  v-model={scope.row.status}
		  	  active-value={1}
		  	  inactive-value={2}
		  	  active-text="启用"
		  	  inactive-text="禁用"
		  	  inline-prompt
		  	  onClick={() => switchStatus(scope as any)}
		  	/>
		  )
		},
		{
		  label: "操作",
		  fixed: "right",
		  slot: "operation"
		}
	  ];
  } else {
	  differentTable = [
	    {
	      label: "IP",
	      prop: "ipAddress"
	    },
	    {
	      label: "端口号",
	      prop: "portNumber"
	    },
	    
	    {
	      label: "操作",
	      fixed: "right",
	      slot: "operation"
	    }
	    
	  ];
  }
  let columns: TableColumnList = [...commonTable, ...differentTable]
  
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getDeviceListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = 1;
    });
    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    getDeviceListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = result.result.current_page;
    });
    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getDeviceListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.per_page;
    pagination.currentPage = result.current_page;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }
  /** 启用/停用*/
  function switchStatus ({ row }) {
  	ElMessageBox.confirm(
  	  `确认要<strong>${
  		row.status === 2 ? "禁用" : "启用"
  	  }</strong><strong style='color:var(--el-color-primary)'>${
  		row.deviceName
  	  }</strong>设备吗?`,
  	  "系统提示",
  	  {
  		confirmButtonText: "确定",
  		cancelButtonText: "取消",
  		type: "warning",
  		dangerouslyUseHTMLString: true,
  		draggable: true
  	  }
  	)
  	  .then(async() => {
  		let params = {
  			deviceId: row.deviceId,
  			status: row.status === 2 ? 2 : 1,
			module: devType
  		}
  		const res = await updateStatusApi(params);
  		if(res.code !== 200) {
  			message(res.msg ?? "操作失败,请联系管理员", {
  			  type: "error"
  			});
  			return
  		}
  		onSearch()
  		
  		message("已成功修改用户状态", {
  			type: "success"
  		});
  	  })
  	  .catch(() => {
  		row.status === 2 ? (row.status = 1) : (row.status = 2);
  	  });
  }
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  function formatHigherDeptOptions(treeList: any) {
      // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
      if (!treeList || !treeList.length) return;
      const newTreeList = [];
      for (let i = 0; i < treeList.length; i++) {
        treeList[i].disabled = treeList[i].status === 0 ? true : false;
        formatHigherDeptOptions(treeList[i].children);
        newTreeList.push(treeList[i]);
      }
      return newTreeList;
    }
  const formInline = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增",
		module: devType,
		status: 1
      };
    } else {
      const res = await getDeviceShowApi({ deviceId: row.deviceId, module: devType });
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      formInline.value = {
        title: "修改",
		module: devType,
        deviceId: res?.result?.deviceId ?? "",
        deviceName: res?.result?.deviceName ?? "",
        deviceAlias: res?.result?.deviceAlias ?? "",
        ipAddress: res?.result?.ipAddress ?? "",
        deviceType: res?.result?.deviceType ?? "",
		warehouseId: res?.result?.warehouseId ?? "",
		portNumber: res?.result?.portNumber ?? "",
		status: res?.result?.status ?? "",
		deviceNo: res?.result?.deviceNo ?? "",
		devicePos: res?.result?.devicePos ?? "",
      };
	  
    }
    addDialog({
      title: `${title}信息`,
      props: {
        formInline: formInline
      },
      width: "44%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              createDeviceApi(curData)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              updateDeviceApi(curData)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();
	
  });

  function handleDelete(row) {
    delDeviceApi({ module: devType, deviceId: row.deviceId }).then((res) => {
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete
  };
}
